package com.google.gsaguide.fragments;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.google.gsaguide.DAO.AmbassadorDAO;
import com.google.gsaguide.MainActivity;
import com.google.gsaguide.R;
import com.google.gsaguide.gplusbridge.GPlusRequestHelper;
import com.google.gsaguide.gplusbridge.OnGPlusRequestListener;
import com.google.gsaguide.gsa.Ambassador;
import com.google.gsaguide.otherlibs.RoundedNetworkImageView;
import com.google.gsaguide.volley.AppController;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * This class shows the AboutFragment and manages all it information.
 * @author Felipe Porge Xavier - http://www.felipeporge.com
 */
public class AboutFragment extends Fragment implements OnGPlusRequestListener, View.OnClickListener {

    private static final String DEBUG_TAG = AboutFragment.class.getSimpleName();
    private static final String URL_GPLUS = "https://plus.google.com/";

    private LinearLayout mDev1;
    private LinearLayout mDev2;
    private LinearLayout mDev3;

    private RoundedNetworkImageView mDevImg1;
    private RoundedNetworkImageView mDevImg2;
    private RoundedNetworkImageView mDevImg3;

    private Context mContext;
    private ImageLoader mImageLoader;
    private GPlusRequestHelper mGPlusRequestHelper;

    private AmbassadorDAO mAmbDB;
    private Ambassador mDevFelipe;
    private Ambassador mDevJordan;
    private Ambassador mDevVictor;

    /**
     * This method returns a new instance of AboutFragment.
     */
    public static AboutFragment newInstance() {
        AboutFragment fragment = new AboutFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_about, container, false);

        // Get the Activity's Context and a new instance of AmbassadorDAO.
        mContext = getActivity().getBaseContext();
        mAmbDB = AmbassadorDAO.getInstance(mContext);

        // Get a new instance of ImageLoader and GPlusRequestHelper.
        mImageLoader = AppController.getInstance().getImageLoader(mContext);
        mGPlusRequestHelper = new GPlusRequestHelper(mContext, this);


        // Set the Google TextView custom font.
        ((TextView) view.findViewById(R.id.about_google_textview)).setTypeface(
                Typeface.createFromAsset(getActivity().getAssets(), "fonts/Catull.TTF"));

        // This code snippet sets the app version in a TextView.
        TextView version = (TextView) view.findViewById(R.id.about_version_textview);
        try {
            PackageInfo info = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0);
            version.setText(getString(R.string.version) + " " + info.versionName.toString());
        } catch (Exception e) {
            if (MainActivity.DEBUG)
                Log.w(DEBUG_TAG, e.getClass().getSimpleName() + " (Set version code)");

            version.setText("");
        }

        // Get Dev1 views and parameters.
        mDev1 = (LinearLayout) view.findViewById(R.id.dev1);
        mDev1.setOnClickListener(this);
        mDevImg1 = ((RoundedNetworkImageView) view.findViewById(R.id.dev1_img));
        mDevImg1.setDefaultImageResId(R.drawable.unknown_user);
        mDevImg1.setErrorImageResId(R.drawable.unknown_user);
        mDevFelipe = mAmbDB.get(getString(R.string.felipe_id));

        // Get Dev2 views and parameters.
        mDev2 = (LinearLayout) view.findViewById(R.id.dev2);
        mDev2.setOnClickListener(this);
        mDevImg2 = ((RoundedNetworkImageView) view.findViewById(R.id.dev2_img));
        mDevImg2.setDefaultImageResId(R.drawable.unknown_user);
        mDevImg2.setErrorImageResId(R.drawable.unknown_user);
        mDevJordan = mAmbDB.get(getString(R.string.jordan_id));

        // Get Dev3 views and parameters.
        mDev3 = (LinearLayout) view.findViewById(R.id.dev3);
        mDev3.setOnClickListener(this);
        mDevImg3 = ((RoundedNetworkImageView) view.findViewById(R.id.dev3_img));
        mDevImg3.setDefaultImageResId(R.drawable.unknown_user);
        mDevImg3.setErrorImageResId(R.drawable.unknown_user);
        mDevVictor = mAmbDB.get(getString(R.string.victor_id));

        // Set the Google Plus profile image in the NetworkImageViews.
        setImage(mDevFelipe, mDevImg1);
        setImage(mDevJordan, mDevImg2);
        setImage(mDevVictor, mDevImg3);

        return view;
    }

    public void setImage(Ambassador amb, NetworkImageView img) {
        if (amb.getPhotoURL() == null) {
            mGPlusRequestHelper.getInfo(amb.getId());
        } else {
            img.setImageUrl(amb.getPhotoURL(), mImageLoader);
        }
    }

    @Override
    public void onPostExecute(JSONObject result, int errorCode) {
        try {
            if (errorCode != 0) {
                // If the DEBUG is true, print this error in LOGCAT.
                if (MainActivity.DEBUG) {
                    Log.w(DEBUG_TAG, errorCode + " Erro (onPostExecute)");
                }

                Toast.makeText(mContext, getString(R.string.volley_error) + " " + errorCode, Toast.LENGTH_SHORT).show();
                return;
            }

            // Get result ID and ImageURL
            String id = result.getString("id");
            String imageURL = result.getJSONObject("image").getString("url").replace("sz=50", "sz=200");

            // Verify what is the result ID and sets each image according with the IDs.
            if (id.equals(mDevFelipe.getId())) {
                mDevImg1.setImageUrl(imageURL, mImageLoader);
                mDevFelipe.setPhotoURL(imageURL);
                mAmbDB.update(mDevFelipe);

            } else if (id.equals(mDevJordan.getId())) {
                mDevImg2.setImageUrl(imageURL, mImageLoader);
                mDevJordan.setPhotoURL(imageURL);
                mAmbDB.update(mDevJordan);

            } else if (id.equals(mDevVictor.getId())) {
                mDevImg3.setImageUrl(imageURL, mImageLoader);
                mDevVictor.setPhotoURL(imageURL);
                mAmbDB.update(mDevVictor);
            }

        } catch (JSONException e) {
            // If the DEBUG is true, print this error in LOGCAT.
            if (MainActivity.DEBUG) {
                Log.w(DEBUG_TAG, e.getClass().getSimpleName() + " Erro (onPostExecute)");
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (v == mDev1) // If the user clicks in the Dev1, open his profile.
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(URL_GPLUS + getString(R.string.felipe))));

        if (v == mDev2) // If the user clicks in the Dev2, open his profile.
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(URL_GPLUS + getString(R.string.jordan))));

        if (v == mDev3) // If the user clicks in the Dev3, open his profile.
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(URL_GPLUS + getString(R.string.victor))));
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        // Return the code of this attached fragment.
        ((MainActivity) activity).onSectionAttached(MainActivity.ABOUT_FRAGMENT);
    }

    @Override
    public void onDetach() {
        super.onDetach();

        // Close the database.
        if (mAmbDB != null)
            mAmbDB.close();
    }
}
